/*
 * @Author: your name
 * @Date: 2022-03-17 21:41:57
 * @LastEditTime: 2022-03-20 14:37:56
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \driving\src\user\user.service.ts
 */
import { User } from './entities/user.entity';
import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { CreateUserDto, UserInfoDto, UsersRo } from './dto/create-user.dto';
import { Repository } from 'typeorm';
import { hashSync} from 'bcryptjs'

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User)
    private userRepository: Repository<User>,
  ) {}
  async register(createUser: CreateUserDto) {
    const { username } = createUser;

    const existUser = await this.userRepository.findOne({
      where: { username },
    });
    if(existUser){
        throw new HttpException("用户名已存在", HttpStatus.BAD_REQUEST)
    }
    const newUser = await this.userRepository.create(createUser)
    return await this.userRepository.save(newUser);
  }



  async findOne(id: string) {
    return await this.userRepository.findOne(id);
  }

  async findByOpenid(openid: string) {
    return await this.userRepository.findOne({ where: { openid } });
  }
  // 获取全部用户的个人信息
  async getAllUser(post):Promise<UsersRo>{
    const qb = await this.userRepository
     .createQueryBuilder('user')
     .where('1=1')
     const Total = await qb.getCount();
     const { pageSize,pageNum } = post
     qb.limit(pageSize)
     qb.offset(pageSize * (pageNum - 1))
     let Users = await qb.getMany();
     const result:UserInfoDto[] = Users.map(item => item.toResponseObject())
     return {list:result,Total:Total}
  }
  // 删除指定用户
  async deleteUser(id):Promise<any>{
    const user = await this.userRepository.findOne(id)
    return await this.userRepository.remove(user)
  }
  // 修改用户个人信息
  async updateUser(post):Promise<any>{
    const qb = await this.userRepository
      .createQueryBuilder('user')
      .where('user.id=:id')
      .setParameter('id',post.id)
    const nowPassword = (await qb.getOne()).password
    let {username, nickname,password,avatar,number} = post
    if(nowPassword === password || !password){
      const result = await this.userRepository.update(post.id,{username:username,nickname:nickname,
        avatar:avatar,number:number})
        return '修改个人信息成功'
    }else{
      password = await hashSync(password)
      const result = await this.userRepository.update(post.id,{username:username,nickname:nickname,
      password:password,avatar:avatar,number:number})
      return '修改个人信息和密码成功'
    }
  }

  // 获取全部学员列表 
  async getAllTrainee():Promise<any>{
    const qb = await this.userRepository
      .createQueryBuilder('user')
      .where('user.role =:role',{role:'trainees'})
    const Users =await qb.getMany()
    const result:UserInfoDto[] =  Users.map(item => item.toResponseObject())
    return {list:result}
  }
  // 查看个人详情信息
  async getUserDeil(id):Promise<any>{
    return await this.userRepository.findOne(id)
  }

  // 查看个人详情信息
  async getUserDeilById(id):Promise<any>{
    return await this.userRepository.findOne(id)
  }
}
